#!/usr/bin/perl

use strict;
use warnings;
use Flickr::API;
use Digest::MD5 qw(md5_hex);
use XML::Parser::Lite::Tree;

my $key;
my $secret;
my $frob;

my $var_name = '';
foreach(@ARGV){
	$key = $_ if $var_name eq "-k" && !/^-/;
	$secret = $_ if $var_name eq "-c" && !/^-/;
	$frob = $_ if $var_name eq "-f" && !/^-/;
	$var_name = $_ if /^-/;
}

unless(defined($key)){
	print "input your flickr api_key: ";
	$key = <STDIN>;
	chomp($key);
}

unless(defined($secret)){
	print "\ninput your api_key secret: ";
	$secret = <STDIN>;
	chomp($secret);
	print "\n";
}

my $api = new Flickr::API({'key' => $key, 'secret' => $secret});

my $response;
my $api_sig;
my $link_url;
if(!defined($frob)){
	print "Geting frob...\t";
	$response = $api->execute_method('flickr.auth.getFrob');	
	$frob = $response->{tree}->{children}->[1]->{children}->[0]->{content};
	#$frob = '6953507-b1e5432d4efbfd42';
	print "frob: $frob\n\n";

	$api_sig = md5_hex($secret . 'api_key' . $key . 'frob' . $frob . 'permsdelete');
	$link_url = "http://www.flickr.com/services/auth/?api_key=$key&perms=delete&frob=$frob&api_sig=$api_sig";
	print "1. Enter the following URL into your browser\n\n",
      "$link_url\n\n",
      "2. Follow the instructions on the web page\n",
      "3. Hit <Enter> when finished.\n\n";
	<STDIN>;
}else{
	print "frob: $frob\n\n";
}

$response = $api->execute_method('flickr.auth.getToken',{'frob' => $frob});
print $response->content;
my $token = $response->{tree}->{children}->[1]->{children}->[1]->{children}->[0]->{content};
print "token: $token\n";

open CONFIG, "> $ENV{HOME}/.flickpr" or die "$!";
print CONFIG "# flickpr config file\n",
	"# version: 0.1.0\n",
	"# author: nowa\n",
	"# contact: nowazhu\@gmail.com\n",
	"# homepage: http://www.nowazhu.com\n\n";
print CONFIG "api_key=$key\n",
		"secret=$secret\n",
		"frob=$frob\n",
		"perms=delete\n",
		"spi_sig=$api_sig\n",
		"auth_token=$token";
print "done.\n";

#解析xml
sub response_tag {
	my $t = shift;
	my $node = shift;
	my $tag = shift;

	return undef unless defined $t and exists $t->{'children'};

	for my $n ( @{$t->{'children'}} ) {
		next unless defined $n and exists $n->{'name'} and exists $n->{'children'};
		next unless $n->{'name'} eq $node;

		for my $m (@{$n->{'children'}} ) {
			next unless exists $m->{'name'}
				and $m->{'name'} eq $tag
				and exists $m->{'children'};

			return $m->{'children'}->[0]->{'content'};
		}
	}
	return undef;
}
